<template>
  <div class="login-wrapper">
    <!-- 头像logo -->
    <div class="login-logo">
      <van-image :src="imgUrl"></van-image>
    </div>
    <!-- 表单 -->
    <div class="login-form">
			<Vprovform :provFormData="provFormData" @submit="handleLogin" ref="loginFormRef" validate-trigger="onSubmit">
			</Vprovform>
      <van-config-provider :theme-vars="themeVars">
        <van-form @submit="handleLogin" ref="loginFormRef" validate-trigger="onSubmit">
          <van-cell-group inset>
            <van-field
              ref="usernameRef"
              v-model="loginForm.username"
              name="validateMobile"
              maxlength="11"
              placeholder="请输入手机号"
              :rules="loginRules.username"
            />
            <van-field
              ref="passwordRef"
              :right-icon="passwordType === 'password' ? 'closed-eye' : 'eye-o'"
              v-model="loginForm.password"
              :type="passwordType"
              name="validatePassword"
              placeholder="请输入密码"
              @click-right-icon="showPwd"
              :rules="loginRules.password"
            />
          </van-cell-group>
          <div class="btn-box">
            <van-button
              round
              block
              :loading="loading"
              loading-type="spinner"
              type="primary"
              native-type="submit"
            >
              登 陆
            </van-button>
          </div>
        </van-form>
      </van-config-provider>
      <!-- 立即注册 -->
      <div class="login-textlist">
        <span @click="goPage('register')">立即注册</span> |
        <span>忘记密码</span>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted } from 'vue'
import { Form, Notify } from 'vant'
import { useRouter } from 'vue-router'
import { validateMobile, validatePassword } from '@utils/validate'
import { useStore } from 'vuex'
import { IGlobalState } from '@/store'
import useRouteQuery from './hooks/useRouteQuery'
import { uuid } from 'vue-uuid'
import * as Types from '@/store/action-types'
import { Encrypt, getImgUrl } from '@utils/index';
import Vprovform from '@comp/provForm/index.vue';

type IVantFromInstance = InstanceType<typeof Form>
export default defineComponent({
  name: 'Login',
	components:{Vprovform},
  setup() {
    let store = useStore<IGlobalState>()
    const router = useRouter()
    const loading = ref(false) // 登录加载状态
    // form ref
    const loginFormRef = ref<IVantFromInstance | null>(null)
    // form username ref
    const usernameRef = ref<HTMLInputElement | null>(null)
    // form password ref
    const passwordRef = ref<HTMLInputElement | null>(null)

    // themeVars 内的值会被转换成对应 CSS 变量
    // 比如 sliderBarHeight 会转换成 `--van-slider-bar-height`
    const themeVars = {
      buttonPrimaryBorderColor: '#3CB677',
      buttonPrimaryBackgroundColor: '#3CB677',
    }
    // logo
    const imgUrl = getImgUrl('login-logo.png')

    // uuid
    let uuId = ref(uuid.v1())

    const loginState = reactive({
      loginForm: {
        username: '13512345678', //13512345678
        password: '123wer!@', //123wer!@
        uuid: uuId,
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: 'onBlur',
            message: '请输入手机号码！',
          },
          { trigger: 'onBlur', validator: validateMobile, message: '请输入合法格式的手机号码' },
        ],
        password: [
          {
            required: true,
            trigger: 'onBlur',
            message: '请输入密码！',
          },
          {
            trigger: 'onBlur',
            validator: validatePassword,
            message: '密码必须由数字、字母、特殊字符组合',
          },
        ],
      },
      passwordType: 'password',
    })

    // 显示密码
    const showPwd = () => {
      loginState.passwordType = loginState.passwordType === 'password' ? 'text' : 'password'
    }
    // 重定向router query处理
    const { redirect, otherQuery } = useRouteQuery()

    // login
    const handleLogin = (_values: any) => {
      loading.value = true
      //加密
      let { uuid, username, password } = loginState.loginForm
      let encryptWord = Encrypt(
        password,
        uuid.slice(0, 16),
        uuid.slice(uuid.length - 16, uuid.length)
      )
      let param = { uuid, username, password: encryptWord }
      // 发送登陆请求
      store
        .dispatch(`user/${Types.SET_LOGIN}`, param)
        .then((_res: any) => {
          console.log(_res)
          // 登录成功后跳转之前被访问页或首页
          router.push({
            path: redirect.value || '/',
            query: otherQuery.value,
          })
        })
        .catch((_err: any) => {
          loading.value = false
          Notify({ type: 'danger', message: _err })
        })
    }
    //跳转页面
    const goPage = (urlName: string) => {
      router.push({
        path: redirect.value || '/' + urlName,
        query: otherQuery.value,
      })
    }

		
    // 自动获取焦点
    onMounted(() => {
      if (loginState.loginForm.username === '') {
        ;(usernameRef.value as HTMLInputElement).focus()
      } else if (loginState.loginForm.password === '') {
        ;(passwordRef.value as HTMLInputElement).focus()
      }
    })


		//provFormData
		const provFormData = {
			formlist:[
				{
					value:'',//默认值
					type:'text', //类型
					label:"", //title
					icon:"",//icon
					rules:"",//规则
					model:"", // 绑定数据
				}
			],//组件对象list
			// 提交事件
			btn:[""]
		}
    return {
			provFormData,
      themeVars,
      imgUrl,
      loading,
      loginFormRef,
      usernameRef,
      passwordRef,
      handleLogin,
      showPwd,
      goPage,
      ...toRefs(loginState),
    }
  },
})
</script>
<style lang="scss">
@import '@/styles/viriables.scss';
@import '@/styles/mixins.scss';
.login-wrapper {
  width: 100%;
  box-sizing: border-box;
  margin-top: 100px;
  @include flexCenter();
  .login-logo {
    @include circle(39px);
    padding: 5%;
    background-color: $main-color;
    margin-bottom: 40px;
  }
  .login-form {
    width: 80%;
  }
  .btn-box {
    margin: 22px;
  }
  .login-textlist {
    margin: 15px 0;
    color: $secondary-font-color;
    text-align: center;
    span {
      font-size: $fnSize12;
      margin: 0 10px;
    }
  }
}
</style>
